import { FC, useEffect, useRef, useState } from 'react';

interface LazyImageProps {
  src: string | undefined | null;
  alt: string;
  className?: string;
}

const LazyImage: FC<LazyImageProps> = ({ src, alt, className }) => {
  const [isIntersecting, setIsIntersecting] = useState(false);
  const imageRef = useRef<HTMLImageElement>(null);

  useEffect(() => {
    const node = imageRef.current;
    if (!node) return;

    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setIsIntersecting(true);
        observer.unobserve(entry.target);
      }
    });

    observer.observe(node);

    return () => {
      observer.unobserve(node);
    };
  }, [src]); // 如果 src 变化，会重新绑定 observer

  if (!src) {
    return (
      <div
        className={className}
        style={{ width: '100%', height: '100%' }}
      ></div>
    );
  }

  return (
    <img
      ref={imageRef}
      src={isIntersecting ? src : ''}
      alt={alt}
      className={className}
      style={{ width: '100%', height: '100%', objectFit: 'cover' }}
    />
  );
};

export default LazyImage;
